# encoding: utf-8

from PyQt5.Qt import *
from widget.my_window import MyWindow
import configparser
import os
from widget.info_box import InfoBox
import time
import _thread
from functools import partial


class DbInitWindow(MyWindow):
    '''
    sqlserver配置 窗口
    '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_StyledBackground, False)
        # 窗口置顶
        self.setWindowModality(Qt.ApplicationModal)
        # 父窗口实例对象
        self.my_parent_window = kwargs['my_parent']
        # 窗口标题
        self.label_title = QLabel(self)
        self.label_title.resize(230, 40)
        self.label_title.setText('连接配置选择')
        self.label_title.move(10, 5)

        self.setup_ui()

    def get_init_file_cf(self):
        cf = configparser.ConfigParser()
        print(qApp.cx_project_root + r'/init_file/init/sqlserver_db_init.ini')
        cf.read(qApp.cx_project_root + r'/init_file/init/sqlserver_db_init.ini')
        return cf

    def init_write(self, cf):
        cf.write(open(qApp.cx_project_root + r'/init_file/init/sqlserver_db_init.ini', "w"))

    def setup_ui(self):
        # 初始化配置文件
        self.cf = self.get_init_file_cf()

        # # 新增按钮
        # self.test_btn = QPushButton(self)
        # self.test_btn.setText('新增')
        # self.test_btn.move(790, 67)
        # self.test_btn.resize(60, 30)
        # self.test_btn.clicked.connect(self.open_add_db_window)

        # 数据库配置表
        self.init_table()

        # 底部确定取消按钮
        self.init_common_btn()

    def init_table(self):
        '''
        加载数据表
        :return:
        '''
        self.table1 = QTableWidget(self)
        self.table1.resize(800, 370)
        self.table1.move(50, 80)
        # 设置表格的列数为2列
        self.table1.setColumnCount(7)
        # self.table1.setVerticalHeaderLabels(["第一列", "第二列"])
        # 设置表格每列的宽度
        self.table1.setColumnWidth(0, 120)
        self.table1.setColumnWidth(1, 100)
        self.table1.setColumnWidth(2, 110)
        self.table1.setColumnWidth(3, 110)
        self.table1.setColumnWidth(4, 110)
        self.table1.setColumnWidth(5, 100)
        self.table1.setColumnWidth(6, 80)
        # self.table1.setColumnWidth(2, 80)
        # print(field_list)

        # 刷新表格
        self.refresh()
        # 表格监听表，如果表选择框改变，那么刷新表格
        # self.choice_table_comb.currentTextChanged.connect(self.refresh)

    def refresh(self):
        self.table1.clear()
        self.table1.setHorizontalHeaderLabels(["服务器", "端口号", "数据库名", "用户名", "密码", "操作", "选择"])
        # 初始化类，打开配置文件
        secs = self.cf.sections()
        # print(secs)
        secs.remove('current_choice')
        if not secs:
            return
        for i, sec in enumerate(secs):
            self.table1.setRowCount(len(secs))
            opts = self.cf.options(sec)
            for k, opt in enumerate(opts):
                value = self.cf.get(sec, opt)
                print(value)
                self.table1.setItem(i, k, QTableWidgetItem(value))

            # 删除按钮
            self.del_btn = QPushButton()
            self.del_btn.setText('删除')
            server_name = self.table1.item(i, 0).text()
            port = self.table1.item(i, 1).text()
            db_name = self.table1.item(i, 2).text()
            db_key = '{0}_{1}_{2}'.format(server_name, port, db_name)
            self.del_btn.clicked.connect(partial(self.delete_db_init, db_key, i))
            self.table1.setCellWidget(i, 5, self.del_btn)

            # 单选按钮
            radio_box = QRadioButton()
            radio_box.setStyleSheet('margin-left: 30px')
            self.table1.setCellWidget(i, 6, radio_box)
        cur_choice = self.cf.getint("current_choice", "num")
        if cur_choice != -1:
            self.table1.cellWidget(cur_choice, 6).setChecked(True)

    # def open_add_db_window(self):
    #     self.add_db_window = AddDbWindow(width=700, height=200, my_parent=self)
    #     self.add_db_window.show()

    def init_common_btn(self):
        '''
        底部的 确定 和 取消 按钮
        :return:
        '''
        # 确定按钮
        self.btn2 = QPushButton(self)
        self.btn2.setText("确定")
        self.btn2.move(620, 490)
        def field_get():
            if self.table1.rowCount() > 0:
                for i in range(self.table1.rowCount()):
                    if self.table1.cellWidget(i, 6).isChecked():
                        self.my_parent_window.server_input.setText(self.table1.item(i, 0).text())
                        self.my_parent_window.port_input.setText(self.table1.item(i, 1).text())
                        self.my_parent_window.db_name_input.setText(self.table1.item(i, 2).text())
                        self.my_parent_window.username_input.setText(self.table1.item(i, 3).text())
                        self.my_parent_window.password_input.setText(self.table1.item(i, 4).text())
                        self.cf.set("current_choice", "num", str(i))
                        self.init_write(self.cf)
                        self.close_btn.click()
                        return
            self.info_box1 = InfoBox('未选择配置')
            self.info_box1.show()
            def show_1s(info_box):
                '''
                提示框展示一秒后销毁
                :param info_box:
                :return:
                '''
                time.sleep(1)
                info_box.close()
            _thread.start_new_thread(show_1s, (self.info_box1,))
        self.btn2.clicked.connect(field_get)

        # 取消按钮
        self.btn3 = QPushButton(self)
        self.btn3.setText("取消")
        self.btn3.move(720, 490)
        # 点击取消，触发右上角关闭按钮事件
        self.btn3.clicked.connect(self.close_btn.click)

    def delete_db_init(self, db_key, i):
        '''
        删除某个数据库连接的配置
        :return:
        '''
        print('db_key: {0}'.format(db_key))
        self.cf.remove_section(db_key)
        # 重新定位当前选择配置 ----------start------------------------
        cur_choice = self.cf.getint("current_choice", "num")
        if i == cur_choice:
            cur_choice = -1
        if i < cur_choice:
            cur_choice = cur_choice - 1
        self.cf.set("current_choice", "num", str(cur_choice))
        # 重新定位当前选择配置 -----------end-----------------------
        self.init_write(self.cf)
        self.refresh()



# class AddDbWindow(MyWindow):
#     '''
#     增加新数据库配置 窗口
#     '''
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.setAttribute(Qt.WA_StyledBackground, False)
#         # 窗口置顶
#         self.setWindowModality(Qt.ApplicationModal)
#         # 父窗口实例对象
#         self.my_parent_window = kwargs['my_parent']
#         # 窗口标题
#         self.label_title = QLabel(self)
#         self.label_title.resize(230, 40)
#         self.label_title.setText('Sql-server 来源配置')
#         self.label_title.move(10, 5)
#         self.setup_ui()
#
#     def setup_ui(self):
#         # 输入服务器label -------------------------------------------------
#         self.server_label = QLabel(self)
#         self.server_label.setText('服务器：')
#         self.server_label.setFixedWidth(100)
#         self.server_label.move(50, 60)
#         # input
#         self.server_input = QLineEdit(self)
#         # self.server_input.setText('192.168.0.6')
#         # self.server_input.setText('127.0.0.1')
#         # self.server_input.setText('192.168.0.193')
#         # self.server_input.setText('192.168.0.56')
#         self.server_input.setFixedWidth(120)
#         self.server_input.move(120, 57)
#
#         # 输入用户名label -------------------------------------------------
#         self.username_label = QLabel(self)
#         self.username_label.setText('用户名：')
#         self.username_label.setFixedWidth(100)
#         self.username_label.move(50, 110)
#         # input
#         self.username_input = QLineEdit(self)
#         # self.username_input.setText('sa')
#         self.username_input.setFixedWidth(120)
#         self.username_input.move(120, 104)
#
#         # 输入数据库名称label -------------------------------------------------
#         self.db_name_label = QLabel(self)
#         self.db_name_label.setText('数据库名：')
#         self.db_name_label.setFixedWidth(100)
#         self.db_name_label.move(470, 60)
#         # input
#         self.db_name_input = QLineEdit(self)
#         # self.db_name_input.setText('standarddb')
#         # self.db_name_input.setText('cjg2cxstar')
#         # self.db_name_input.setText('sckj2cxstarTP')
#         self.db_name_input.setFixedWidth(120)
#         self.db_name_input.move(550, 57)
#
#         # 输入端口号label -------------------------------------------------
#         self.port_label = QLabel(self)
#         self.port_label.setText('端口号：')
#         self.port_label.setFixedWidth(100)
#         self.port_label.move(260, 60)
#         # input
#         self.port_input = QLineEdit(self)
#         # self.port_input.setText('1433')
#         self.port_input.setFixedWidth(120)
#         self.port_input.move(330, 57)
#
#         # 输入密码label -------------------------------------------------
#         self.password_label = QLabel(self)
#         self.password_label.setText('密码：')
#         self.password_label.setFixedWidth(100)
#         self.password_label.move(260, 110)
#         # input
#         self.password_input = QLineEdit(self)
#         # self.password_input.setText('cxstar2014')
#         # self.password_input.setText('cxstar@2014')
#         # self.password_input.setText('cxstar2012')
#         self.password_input.setFixedWidth(120)
#         self.password_input.move(330, 104)
#
#         # 选择已有库
#         self.test_btn = QPushButton(self)
#         self.test_btn.setText('确定')
#         self.test_btn.move(520, 97)
#         self.test_btn.resize(60, 30)
#         # self.test_btn.clicked.connect(self.open_sqlerver_db_init_window)